# -*- coding: utf-8 -*-

import logging

from xadmin.model.objects import MalformedXMLException, AttributeValueException
from xadmin.lib.administrators import ResourceAdministrator, ResourceNotFoundException
from xadmin.lib.base import *

log = logging.getLogger(__name__)

class ResourceController(BaseController):
    """REST Controller styled on the Atom Publishing Protocol"""

    def __init__(self):
        self.cls = ''
        self.admin = ResourceAdministrator(self.cls)
        self.resource = ''


    def index(self, format='html'):
        """GET /resource: All items in the collection."""
        c.items_url = "/%s" % self.resource
        c.items = self.admin.getAll()
        response.headers['Content-Type'] = 'text/xml; charset=utf-8'
        return render('/%s/list.mako' % self.resource)

    def create(self):
        """POST /resource: Create a new item."""
        try:
            content = request.body.read(int(request.environ['CONTENT_LENGTH']))
            log.debug("Creating resource %s from xml %s" % (self.resource, content))
            itemid = self.admin.create(content)
            self.response_create()
            return "/%s/%s" %(self.resource, itemid)
        except (AttributeValueException, MalformedXMLException, Exception), e:
            abort(400, e.message)

    def new(self, format='html'):
        """GET /resource/new: Form to create a new item."""
        pass

    def update(self, id):
        """PUT /resource/id: Update an existing item."""
        try:
            content = request.body.read(int(request.environ['CONTENT_LENGTH']))
            log.debug("Updating resource %s with id %s from xml %s" % (self.resource, id, content))
            itemid = self.admin.update(id, content)
            self.response_update()
            return "/%s/%s" %(self.resource, itemid)
        except ResourceNotFoundException, e:
            abort(404, e.message)
        except (AttributeValueException, MalformedXMLException, Exception), e:
            abort(400, e.message)

    def delete(self, id):
        """DELETE /resource/id: Delete an existing item."""
        log.debug("Deleting resource %s with id %s" % (self.resource, id))
        self.admin.delete(id)
        self.response_delete()

    def show(self, id, format='html'):
        """GET /resource/id: Show a specific item."""
        try:
            c.item = self.admin.getById(id)
            response.headers['Content-Type'] = 'text/xml; charset=utf-8'
            return render('/%s/view.mako' % self.resource)
        except ResourceNotFoundException, e:
            abort(404)

    def edit(self, id, format='html'):
        """GET /resource/id;edit: Form to edit an existing item."""
        pass
